import random
import time
from database import Mysql
import conf


def update_check(db):

    # 检验人员信息
    check_person_id = conf.check_dept_staff["id"]
    check_person_name = conf.check_dept_staff["name"]

    # 随机时间范围 (毫秒)
    random_6_12min = random.randint(6, 12) * 60 * 1000  # 6-12分钟
    random_120_600s = random.randint(120, 600) * 1000  # 120-600秒

    ####################################################################################################################
    ####################################################################################################################

    # 1、更新检验任务时间（和生产工单相关联）
    sql1 = """
        UPDATE mes_check_task mct
        JOIN mes_task_work_order MTWO ON mct.wip_id = MTWO.wip_id
        SET 
            mct.check_time = MTWO.actual_end_time + %s,
            mct.create_time = MTWO.actual_end_time,
            mct.last_update_time = MTWO.actual_end_time + %s,
            check_person_id = %s,
            check_person_name = %s
    """
    count1 = db.update(
        sql1, (random_6_12min, random_6_12min, check_person_id, check_person_name)
    )
    print(f"sql1 更新检验任务时间: 影响 {count1} 行")

    # 2、更新来料检工单时间（和采购订单相关联）
    sql2 = """
        UPDATE mes_check_task mct
        JOIN purchase_order_info POI ON mct.purchase_no = POI.code
        SET 
            mct.check_time = POI.audit_time + %s,
            mct.create_time = POI.audit_time,
            mct.last_update_time = POI.audit_time,
            check_person_id = %s,
            check_person_name = %s
    """
    count2 = db.update(sql2, (random_120_600s, check_person_id, check_person_name))
    print(f"sql2 更新来料检工单时间: 影响 {count2} 行")

    # 3、不合格品处理
    # 第一个UPDATE语句 - 更新与mes_check_task关联的不合格处理记录
    sql3_1 = """
        UPDATE mes_unqualified_handler uq
        JOIN mes_check_task ct ON uq.relate_no = ct.check_task_no
        SET 
            uq.check_time = ct.check_time,
            uq.submit_time = ct.create_time,
            uq.create_time = ct.create_time,
            uq.last_update_time = ct.create_time,
            uq.assignee_time = ct.create_time + (FLOOR(5 + RAND() * 6) * 60 * 1000)
        WHERE 
            uq.relate_no = ct.check_task_no
    """
    count3_1 = db.update(sql3_1)
    print(f"sql3_1 更新与检验任务关联的不合格处理记录: 影响 {count3_1} 行")

    # 第二个UPDATE语句 - 更新与工单异常关联的不合格处理记录
    sql3_2 = """
        UPDATE mes_unqualified_handler uq
        JOIN mes_task_work_order_ex ex ON uq.relate_no = ex.ex_no
        SET 
            uq.check_time = ex.create_time,
            uq.submit_time = ex.create_time,
            uq.create_time = ex.create_time,
            uq.last_update_time = ex.create_time,
            uq.assignee_time = ex.create_time + (FLOOR(5 + RAND() * 6) * 60 * 1000)
        WHERE 
            uq.wip_id IS NOT NULL
            AND uq.relate_no = ex.ex_no
    """
    count3_2 = db.update(sql3_2)
    print(f"sql3_2 更新与工单异常关联的不合格处理记录: 影响 {count3_2} 行")

    db.commit()
